#include "config.h"



Fast::config::config(const std::string &fn)
{
    filename = fn;

    std::string ext =SplitFilename(filename);
    if("json" == ext){
        ext_format = T_JSON;
    }else if ("info" == ext|| "config" == ext|| "sys" == ext) {
        ext_format = T_INFO;
    }else if ("xml" == ext) {
        ext_format = T_XML;
    }else if ("ini" == ext) {
        ext_format = T_INI;
    }else {
        ext_format = -1;
    }


    switch (ext_format) {
    case T_JSON:
        boost::property_tree::read_json(filename,pt);
        break;
    case T_INFO:
        boost::property_tree::read_info(filename,pt);
        break;
    case T_XML:
        boost::property_tree::read_xml(filename,pt);
        break;
    case T_INI:
        boost::property_tree::read_ini(filename,pt);
        break;
    default:
        std::cout <<"-->" << "Error format: "<< filename <<std::endl;
        break;
    }

}

void Fast::config::sync()
{
    this->write2File();
}

void Fast::config::write2File()
{
    std::ostringstream outputStream;
    switch (ext_format) {
    case T_INI:
        boost::property_tree::ini_parser::write_ini(outputStream, pt,false);
        break;
    case T_INFO:
        boost::property_tree::info_parser::write_info(outputStream, pt);
        break;
    case T_JSON:
         boost::property_tree::json_parser::write_json(outputStream, pt,false);
        break;
    case T_XML:
        boost::property_tree::xml_parser::write_xml(outputStream, pt,false);
        break;
    default:
        std::cout <<"Error format:" << ext_format <<std::endl;
        return ;
    }

    std::ofstream tmpReport(filename);
    if(!tmpReport){
        std::cout <<"文件不能打开:" << filename <<std::endl;
    }else{
        tmpReport<<outputStream.str();
    }
    tmpReport.close();
}
